package Server

import (
	"fmt"

	"github.com/TarsCloud/TarsGo/tars"
	"github.com/TarsCloud/TarsGo/tars/util/conf"
	"github.com/bwmarrin/snowflake"
	"github.com/wzh200x/gdbServer/db/dbMysql"
	"github.com/wzh200x/gdbServer/db/models"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/gdbServerProtocol"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

type GDBServer struct {
	dbHepler *dbMysql.MysqlHelper
	nodes    [hyperNexusType.TableShardingNum]*snowflake.Node
}

func (gdb *GDBServer) Init(comm *tars.Communicator, sConf *conf.Conf) error {
	err := gdb.dbHepler.Init(sConf)
	if err != nil {
		fmt.Printf("dbHepler init fail, err:(%s)\n", err)
		return err
	}
	models.RegisterEntityModel(gdb.dbHepler)
	// 初始化snowflake
	for i := 0; i < hyperNexusType.TableShardingNum; i++ {
		node, err := snowflake.NewNode(int64(i))
		if err != nil {
			fmt.Printf("snowflake init fail, err:(%s)\n", err)
			return err
		}
		gdb.nodes[i] = node
	}
	// 初始化tars
	gdb.RegisterTarsObj()
	return nil
}

func (gdb *GDBServer) GetDBHelper() *dbMysql.MysqlHelper {
	return gdb.dbHepler
}

func (gdb *GDBServer) InitFinish() error {
	gdb.dbHepler.SyncTable()
	return nil
}

func (gdb *GDBServer) Info() string {
	return fmt.Sprintf(`server :%s version :%s`, "gdbServer", "0.0.1")
}

func (gdb *GDBServer) Name() string {
	return "gdbServer"
}

func (gdb *GDBServer) Stop() error {
	return nil
}

func (gdb *GDBServer) RegisterTarsObj() {
	// Get server config
	cfg := tars.GetServerConfig()
	// New servant imp
	imp := new(DBOperateImp)
	app := new(gdbServerProtocol.GDBServer)
	// Register Servant
	app.AddServantWithContext(imp, cfg.App+"."+cfg.Server+".DBOperateObj")
}

func (gdb *GDBServer) GenerateID(shardIndex int) int64 {
	return gdb.nodes[shardIndex].Generate().Int64()
}

func NewGDBServer() *GDBServer {
	gs := &GDBServer{
		dbHepler: dbMysql.NewMysqlHelper(),
	}
	return gs
}

var GDBApp *GDBServer = NewGDBServer()
